﻿using AchieveBLL;
using AchieveCommon;
using AchieveEntity;
using AchieveManageWeb.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Text;

namespace AchieveManageWeb.Controllers
{
    [AchieveManageWeb.App_Start.JudgmentLogin]
    public class HomeController : Controller
    {
        //
        // GET: /Home/ 
        public ActionResult Index()
        {
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            if (uInfo == null)
            {
                return RedirectToAction("Index", "Login");
            }
            ViewBag.RealName = uInfo.RealName;
            ViewBag.TimeView = DateTime.Now.ToLongDateString();
            ViewBag.DayDate = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek);
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "系统首页")); //日志记录
            return View();
        }


        public ActionResult IndexNew()
        {
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            if (uInfo == null)
            {
                return RedirectToAction("Index", "Login");
            }
            ViewBag.RealName = uInfo.RealName;
            ViewBag.TimeView = DateTime.Now.ToLongDateString();
            ViewBag.DayDate = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek);
            return View();
        }
        public ActionResult WeekOper()
        {
            return View();
        }
        /// <summary>
        /// 查询出数据显示在菜单栏目中
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadMenuData()
        {
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            string menuJson = new MenuBLL().GetUserMenu(uInfo.ID);
            return Content(menuJson);
        } 


        /// <summary>
        /// 通用产能预警查询，处理计划预估委外等分类预警、分工艺预警，分周、月等周期；
        /// 调用参数：1、key【columns|datarows】请求数据类型;2、cycle【week|month】统计周期；3、removefinished【true|false】是否过滤已完成任务单；
        /// 4、refresh【true|false】是否强制重新计算数据；5、classifyOper【true|false】是否分工序统计产能；5、department【sw,ml,ec,sd,mf，all】分部门统计要求
        /// 6、adjustNum【int】调整周期数量；7、
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCapacityAlert()
        {
            string key = Request["key"] ?? "";//判断当前ajax请求的是列名还是数据； 
            string cycle = Request["cycle"] ?? "";//周期
            string dataType = Request["dataType"] ?? "";// dataType:"monthOperEst",目前仅用于月预估工序产能预警，与项目管理预估成本关联
            if (key == "" || cycle == "")
            {
                return Content("{\"total\": " + 0 + ",\"rows\":" + "请求参数不全！" + "}");
            }
            bool removefinished = Request["removefinished"] == null ? false : Convert.ToBoolean(Request["removefinished"]);//是否过滤已完成的订单，默认不关闭
            bool refresh = Request["refresh"] == null ? false : Convert.ToBoolean(Request["refresh"]);// 20190301
            bool classifyOper = Request["classifyOper"] == null ? false : Convert.ToBoolean(Request["classifyOper"]);//判断当前ajax请求的数据是否分工艺，false即将所有工艺汇总成一行输出；
            int adjustNum = Request["adjustNum"] == null ? 0 : Convert.ToInt32(Request["adjustNum"]);//周或月的调整前后数，往后调整为负值 

            string department = Request["department"] == null ? "all" : Request["department"].ToString();//department参数表示部门，分部门统计数据；sw,ml,ec,sd,mf,all     
            string schedule = Request["schedule"] == null ? "plan" : Request["schedule"].ToString();// 排产方式：系统真实排产计划plan、自动排产autocal

            DateTime startDate, endDate;
            string strJson;//返回结果数据

            switch (cycle)//按周期分类处理
            { 
                    #region 按月处理
                case "month":
                   
                    startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    startDate = startDate.AddMonths(adjustNum);//调整起始月份 
                     #region 计算月列范围和表头
                    if (key == "columns")
                    {
                        string columns = "[{ \"width\": 100, \"title\": \"工艺\", \"field\":\"OperGroupName\", \"sortable\": \"false\" }";
                        columns += ",{ \"width\": 60, \"title\": \"标准月能力\", \"field\":\"DayTime\", \"sortable\": \"false\" }";
                        columns += ",{ \"width\": 20, \"title\": \"预警%\", \"field\":\"AlertValue\", \"sortable\": \"false\" }";
                        for (int i = 0; i <= 6; i++)//取相邻5个月的数据
                        {
                            string cname = startDate.AddMonths(i).ToString("yyyy年MM月");
                            columns += ",{ \"width\": 60, \"title\": \"" + cname + "\", \"field\":\"" + i + "\", \"sortable\": \"false\" }";
                        }
                        columns += "]";
                        return Content("{\"startday\": \"" + startDate.ToString() + "\",\"success\":true" + ",\"columns\":" + columns + "}");
                    }
                          #endregion
                    
                    //查询月预估工艺产能--根据项目成本管理模块的--预估成本进行计算
                    if ( dataType=="monthOperEst")
	                {
                        DataTable dtgroup = CockpitBLL.getWorkTime(cycle, startDate, 6, refresh, removefinished, department, schedule, classifyOper, dataType);
                        strJson = AchieveCommon.JsonHelper.ToJson(dtgroup);
                        return Content("{\"total\": " + dtgroup.Rows.Count + ",\"rows\":" + strJson + "}"); 
	                }
                   

                    if (classifyOper)//分工艺
                    {
                        //CockpitBLL cb = new CockpitBLL();
                        DataTable dtgroup = CockpitBLL.getWorkTime(cycle, startDate, 6, refresh, removefinished, department, schedule, classifyOper);
                        strJson = AchieveCommon.JsonHelper.ToJson(dtgroup);                        
                        return Content("{\"total\": " + dtgroup.Rows.Count + ",\"rows\":" + strJson + "}");
                    } else//不分工艺，甲方要求使用      20190301 目前使用
                    {
                        //tablename = "tbOperValueSW";
                        //原方案中，周计划产能预警只统计选择的工艺
                        //DataTable dt = new CockpitBLL().getOperAlertDataTable(startd, 5, "month",refresh,removefinished);
                        //  DataTable dt = new CockpitBLL().getMonthPlanWorkTime(startd, 6, refresh, removefinished);//计划工时，统计所有工艺
                        //DataTable dt = new CockpitBLL().getMonthPlanWorkTime2(startDate, 6, refresh, removefinished, tablename);//计划工时，统计所有工艺
                        DataTable dt = CockpitBLL.getWorkTime("month", startDate, 6, refresh, removefinished, department, schedule, classifyOper);//计划工时，统计所有工艺
                        
                        DataTable dtNew = new DataTable();
                        dtNew = dt.Copy();
                        dtNew.Rows.Clear();//清空表数据
                        dtNew.Rows.Add("计划工时", "888", 70, 70, 0, 0, 0, 0, 0, 0);//第一行，预警值70%，

                        //dtNew.ImportRow(dt.Rows[0]);//这是加入的是第一行
                        //数据结构：OperGroupName,OperGroupID,DayTime,AlertValue,0,1,2,3,4
                        foreach (DataRow dr in dt.Rows)
                        {

                            if (Convert.ToInt32(dr["OperGroupID"]) > 2000)//表示预估、委外工时
                            {
                                dtNew.ImportRow(dr);//预估工时不变；第二行、第三行，预估确认，预估未确认；
                            }
                            else//其余工时累加到，第一行中；表示计划工时
                            {
                                dtNew.Rows[0]["DayTime"] = Convert.ToDecimal(dr["DayTime"]) + Convert.ToDecimal(dtNew.Rows[0]["DayTime"]);
                                dtNew.Rows[0]["0"] = Convert.ToDecimal(dr["0"]) + Convert.ToDecimal(dtNew.Rows[0]["0"]);
                                dtNew.Rows[0]["1"] = Convert.ToDecimal(dr["1"]) + Convert.ToDecimal(dtNew.Rows[0]["1"]);
                                dtNew.Rows[0]["2"] = Convert.ToDecimal(dr["2"]) + Convert.ToDecimal(dtNew.Rows[0]["2"]);
                                dtNew.Rows[0]["3"] = Convert.ToDecimal(dr["3"]) + Convert.ToDecimal(dtNew.Rows[0]["3"]);
                                dtNew.Rows[0]["4"] = Convert.ToDecimal(dr["4"]) + Convert.ToDecimal(dtNew.Rows[0]["4"]);
                                dtNew.Rows[0]["5"] = Convert.ToDecimal(dr["5"]) + Convert.ToDecimal(dtNew.Rows[0]["5"]); //MODIFY 20190216
                            }
                        }

                        dtNew.Rows.Add("合计工时", "999", 70, 70, 0, 0, 0, 0, 0, 0);//增加合计工时、预警值70%，999为id，
                        dtNew.Columns.Add("sortid", typeof(int));
                        dtNew.Rows[0]["sortid"] = 1;//计划
                        dtNew.Rows[1]["sortid"] = 3;//预估-确认
                        dtNew.Rows[2]["sortid"] = 5;//预估-未确认
                        dtNew.Rows[3]["sortid"] = 2;//委外
                        dtNew.Rows[4]["sortid"] = 4;//合计


                        dtNew.DefaultView.Sort = "sortid asc";//重新设置排序
                        DataTable dtNew2 = dtNew.DefaultView.ToTable(); //保存在一张新表中

                        int x = 3;
                        decimal daytime = 0, c0 = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0;
                        for (int i = 0; i < x; i++)
                        {
                            daytime += Convert.ToDecimal(dtNew2.Rows[i]["DayTime"]);
                            c0 += Convert.ToDecimal(dtNew2.Rows[i]["0"]);
                            c1 += Convert.ToDecimal(dtNew2.Rows[i]["1"]);
                            c2 += Convert.ToDecimal(dtNew2.Rows[i]["2"]);
                            c3 += Convert.ToDecimal(dtNew2.Rows[i]["3"]);
                            c4 += Convert.ToDecimal(dtNew2.Rows[i]["4"]);
                            c5 += Convert.ToDecimal(dtNew2.Rows[i]["5"]);

                        }
                        dtNew2.Rows[x]["DayTime"] = daytime;
                        dtNew2.Rows[x]["0"] = c0;
                        dtNew2.Rows[x]["1"] = c1;
                        dtNew2.Rows[x]["2"] = c2;
                        dtNew2.Rows[x]["3"] = c3;
                        dtNew2.Rows[x]["4"] = c4;
                        dtNew2.Rows[x]["5"] = c5;
                        strJson = AchieveCommon.JsonHelper.ToJson(dtNew2);
                        return Content("{\"total\": " + 5 + ",\"rows\":" + strJson + "}");
                    }
                    
                    //break;
                    #endregion
                #region 按周处理
                case "week":                   
                    int thisweek = DateHelper.GetWeekIndex(DateTime.Now);
                    DateHelper.GetWeek(DateTime.Now.Year, thisweek, out startDate, out endDate);
                    // System.Diagnostics.Debug.WriteLine("年{0}，本周:{1} --日期:{2}--开始时间:{3}--结束时间{4}",DateTime.Now.Year, thisweek,DateTime.Now, startd,endd);
                    startDate = startDate.AddDays(adjustNum * 7);//获取调整后开始统计日期；
                    #region 计算周视图列名
                    if (key == "columns")
                    {
                        string columns = "[{ \"width\": 100, \"title\": \"工艺\", \"field\":\"OperGroupName\", \"sortable\": \"false\" }";
                        columns += ",{ \"width\": 60, \"title\": \"标准周能力\", \"field\":\"DayTime\", \"sortable\": \"false\" }";
                        columns += ",{ \"width\": 20, \"title\": \"预警%\", \"field\":\"AlertValue\", \"sortable\": \"false\" }";
                        for (int i = 0; i < 6; i++)
                        {
                            string cname = string.Empty;
                            int cweek = thisweek + adjustNum + i;//获取每列的周序号               
                            DateTime dts, dte;
                            DateHelper.GetWeek(DateTime.Now.Year, cweek, out dts, out dte);
                            string daterange = "<br/>" + dts.ToString("MM") + "/" + dts.ToString("dd") + "-" + dte.ToString("MM") + "/" + dte.ToString("dd");
                            if (cweek == thisweek)
                            {
                                cname = "本周" + daterange;
                            }
                            else { cname = "第" + cweek + "周" + daterange; }
                            columns += ",{ \"width\": 60, \"title\": \"" + cname + "\", \"field\":\"" + i + "\", \"sortable\": \"false\" }";
                        }
                        columns += "]";
                        return Content("{\"thisweek\": " + thisweek.ToString() + ",\"success\":true" + ",\"columns\":" + columns + "}");
                    }
                    #endregion
                    #region 计算产能数据
                    if (classifyOper)//分工艺统计
                    {
                        //CockpitBLL cb=new CockpitBLL();
                        DataTable dtgroup = CockpitBLL.getWorkTime(cycle, startDate, 6, refresh, removefinished, department, schedule, classifyOper);
                           /// cb.getOperAlertDataTable(startDate, 6, "week", refresh, removefinished, tablename);
                        strJson= AchieveCommon.JsonHelper.ToJson(dtgroup); 
                        return Content("{\"total\": " + 0 + ",\"rows\":" + strJson + "}");

                    } else//分计划、预估、委外等类型统计
                    {
                        DataTable dt = CockpitBLL.getWorkTime("week", startDate, 6, refresh, removefinished, department, schedule, classifyOper);//计划工时，统计所有工艺
                        DataTable dtNew = new DataTable();
                        dtNew = dt.Copy();
                        dtNew.Rows.Clear();//清空表数据
                        dtNew.Rows.Add("计划工时", "888", 70, 70, 0, 0, 0, 0, 0, 0);//第一行，预警值70%，

                        //dtNew.ImportRow(dt.Rows[0]);//这是加入的是第一行
                        //数据结构：OperGroupName,OperGroupID,DayTime,AlertValue,0,1,2,3,4
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (Convert.ToInt32(dr["OperGroupID"]) > 2000)//表示预估、委外工时
                            {
                                dtNew.ImportRow(dr);//预估工时不变；第二行、第三行，预估确认，预估未确认；
                            }
                            else//其余工时累加到，第一行中；表示计划工时
                            {
                                dtNew.Rows[0]["DayTime"] = Convert.ToDecimal(dr["DayTime"]) + Convert.ToDecimal(dtNew.Rows[0]["DayTime"]);
                                dtNew.Rows[0]["0"] = Convert.ToDecimal(dr["0"]) + Convert.ToDecimal(dtNew.Rows[0]["0"]);
                                dtNew.Rows[0]["1"] = Convert.ToDecimal(dr["1"]) + Convert.ToDecimal(dtNew.Rows[0]["1"]);
                                dtNew.Rows[0]["2"] = Convert.ToDecimal(dr["2"]) + Convert.ToDecimal(dtNew.Rows[0]["2"]);
                                dtNew.Rows[0]["3"] = Convert.ToDecimal(dr["3"]) + Convert.ToDecimal(dtNew.Rows[0]["3"]);
                                dtNew.Rows[0]["4"] = Convert.ToDecimal(dr["4"]) + Convert.ToDecimal(dtNew.Rows[0]["4"]);
                                dtNew.Rows[0]["5"] = Convert.ToDecimal(dr["5"]) + Convert.ToDecimal(dtNew.Rows[0]["5"]); //MODIFY 20190216
                            }
                        }

                        dtNew.Rows.Add("合计工时", "999", 70, 70, 0, 0, 0, 0, 0, 0);//增加合计工时、预警值70%，999为id，
                        dtNew.Columns.Add("sortid", typeof(int));
                        dtNew.Rows[0]["sortid"] = 1;//计划
                        dtNew.Rows[1]["sortid"] = 3;//预估-确认
                        dtNew.Rows[2]["sortid"] = 5;//预估-未确认
                        dtNew.Rows[3]["sortid"] = 2;//委外
                        dtNew.Rows[4]["sortid"] = 4;//合计


                        dtNew.DefaultView.Sort = "sortid asc";//重新设置排序
                        DataTable dtNew2 = dtNew.DefaultView.ToTable(); //保存在一张新表中

                        //计算第四行，合计工时；
                        int x = 3;
                        decimal daytime = 0, c0 = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0;
                        for (int i = 0; i < x; i++)
                        {
                            daytime += Convert.ToDecimal(dtNew2.Rows[i]["DayTime"]);
                            c0 += Convert.ToDecimal(dtNew2.Rows[i]["0"]);
                            c1 += Convert.ToDecimal(dtNew2.Rows[i]["1"]);
                            c2 += Convert.ToDecimal(dtNew2.Rows[i]["2"]);
                            c3 += Convert.ToDecimal(dtNew2.Rows[i]["3"]);
                            c4 += Convert.ToDecimal(dtNew2.Rows[i]["4"]);
                            c5 += Convert.ToDecimal(dtNew2.Rows[i]["5"]);

                        }
                        dtNew2.Rows[x]["DayTime"] = daytime;
                        dtNew2.Rows[x]["0"] = c0;
                        dtNew2.Rows[x]["1"] = c1;
                        dtNew2.Rows[x]["2"] = c2;
                        dtNew2.Rows[x]["3"] = c3;
                        dtNew2.Rows[x]["4"] = c4;
                        dtNew2.Rows[x]["5"] = c5;
                        strJson = AchieveCommon.JsonHelper.ToJson(dtNew2);
                        return Content("{\"total\": " + 5 + ",\"rows\":" + strJson + "}");

                    }
                    // string strJson = new CockpitBLL().getOperAlertJson(startd, 6, "week", refresh, removefinished);
                   

                    #endregion

                #endregion
                default:
                    return Content("{\"total\": " + 0 + ",\"rows\":" + "不能识别的请求参数！" + "}");
                 
            }

        }

        /// <summary>
        /// 判断是否修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckIsChangePwd()
        {
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            return Content("{\"msg\":" + new JavaScriptSerializer().Serialize(uInfo) + ",\"success\":true}");
        }

        /// <summary>
        /// 获取导航菜单
        /// </summary>
        /// <param name="id">所属</param>
        /// <returns>树</returns>
        public JsonResult GetTreeByEasyui(string id)
        {
            try
            {
                UserEntity uInfo = ViewData["Account"] as UserEntity;
                if (uInfo != null)
                {
                    DataTable dt = new MenuBLL().GetUserMenuData(uInfo.ID, int.Parse(id));
                    List<SysModuleNavModel> list = new List<SysModuleNavModel>();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        SysModuleNavModel model = new SysModuleNavModel();
                        model.id = dt.Rows[i]["menuid"].ToString();
                        model.text = dt.Rows[i]["menuname"].ToString();
                        model.attributes = dt.Rows[i]["linkaddress"].ToString();
                        model.iconCls = dt.Rows[i]["icon"].ToString();
                        if (new MenuBLL().GetMenuList(" AND ParentId= " + model.id).Rows.Count > 0)
                        {
                            model.state = "closed";
                        }
                        else
                        {
                            model.state = "open";
                        }
                        list.Add(model);
                    }
                    return Json(list);
                }
                else
                {
                    return Json("0", JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json("0"+ex.ToString(), JsonRequestBehavior.AllowGet);
            }
        }


        /// <summary>
        /// 导出Excel，前端采用模拟表单传入数据
        /// </summary>
        /// <returns></returns>
      // public ActionResult ExportExcel()
        public FileStreamResult ExportExcel()
        {
          
            string dg_type = Request.Params["dg_type"];//获取数据视图类型 
            string cycle = Request.Params["cycle"];
            bool removefinished = Convert.ToBoolean( Request.Params["removefinished"]);
            int adjust =Convert.ToInt32( Request.Params["adjust"]);
            string department = Request.Params["department"];
            string schedule = Request.Params["schedule"];
            bool classifyOper = Convert.ToBoolean(Request.Params["classifyOper"]);
            DateTime startDate, endDate; 
            DataTable dt=new DataTable();//输出表格
            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            switch (cycle)
            {
                case   "month":
                    startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    startDate=startDate.AddMonths(-2 + adjust);
                    row1.CreateCell(0).SetCellValue("工艺");
                    row1.CreateCell(1).SetCellValue("工艺组id");
                    row1.CreateCell(2).SetCellValue("标准月能力");
                    row1.CreateCell(3).SetCellValue("预警%"); 
                      
                        for (int i = 0; i <= 6; i++)//取相邻6个月的数据
                        {
                            string cname = startDate.AddMonths(i).ToString("yyyy年MM月");
                            row1.CreateCell(i + 4).SetCellValue(cname); 
                        }
                        dt = CockpitBLL.getWorkTime("month", startDate, 8, false, removefinished, department, schedule, classifyOper);
                    break;
                case "week":
                    int thisweek = DateHelper.GetWeekIndex(DateTime.Now);
                    DateHelper.GetWeek(DateTime.Now.Year, thisweek, out startDate, out endDate);
                    // System.Diagnostics.Debug.WriteLine("年{0}，本周:{1} --日期:{2}--开始时间:{3}--结束时间{4}",DateTime.Now.Year, thisweek,DateTime.Now, startd,endd);
                    startDate = startDate.AddDays((adjust-2) * 7);//获取调整后开始统计日期；
                    row1.CreateCell(0).SetCellValue("工艺");
                    row1.CreateCell(1).SetCellValue("工艺组id");
                    row1.CreateCell(2).SetCellValue("标准周能力");
                    row1.CreateCell(3).SetCellValue("预警%"); 
                      
                        for (int i = 0; i <= 6; i++)//取相邻6个月的数据
                        {
                            string cname = string.Empty;
                            int cweek = thisweek + adjust + i-2;//获取每列的周序号               
                            DateTime dts, dte;
                            DateHelper.GetWeek(DateTime.Now.Year, cweek, out dts, out dte);
                            string daterange = " " + dts.ToString("MM") + "/" + dts.ToString("dd") + "-" + dte.ToString("MM") + "/" + dte.ToString("dd");
                            if (cweek == thisweek)
                            {
                                cname = "本周" + daterange;
                            }
                            else { cname = "第" + cweek + "周" + daterange; }
                            row1.CreateCell(i + 4).SetCellValue(cname); 
                        }
                        dt = CockpitBLL.getWorkTime("week", startDate, 8, false, removefinished, department, schedule, classifyOper);
                    break; 

                default:
                    break;
            }
             
                int k = 1;
                foreach (DataRow item in dt.Rows)
                { 
                    NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(k);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j<4)
                        {
                             rowtemp.CreateCell(j).SetCellValue(item[j].ToString());
                        }
                        else
                        {
                            rowtemp.CreateCell(j).SetCellValue(Convert.ToDouble(item[j].ToString()));
                        }
                       
                    }
                    k++; 
                }
  
 
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", HttpUtility.UrlEncode("导出数据" + dg_type, Encoding.UTF8).ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");

        }
    
    
    }
}
